<?php
namespace control;
/*
*生产领退料明细表类
*/

class pickAndRefundMxClass extends adIndexClass
{
    private const page = 'pickAndRefundMx';
    private const title = '生产领退料明细表';
    private array $typeOption = ['生产领料', '生产退料'];

    /**
     * 字段初始化
     */
    public function fieldInit($fun): array
    {
        switch ($fun) {
            default:
                $tr = [
                    'recordDate'          => [
                        'name'  => "单据日期",
                        'width' => 100,
                        'sort' => 1,
                    ],
                    'orderNo'  => [
                        'name'  => '单据编号',
                        'width' => 150,
                        'sort' => 1,
                    ],
                    'type'         => [
                        'name'  => '业务类型',
                        'width' => 150,
                    ],
                    'pickId'          => [
                        'name'  => '经手人',
                        'width' => 100,
                    ],
                    'code'          => [
                        'name'  => '物料编码',
                        'width' => 150,
                        'sort' => 1,
                    ],
                    'materialName'          => [
                        'name'  => '物料名称',
                        'width' => 150,
                    ],
                    'model'          => [
                        'name'  => '规格型号',
                        'width' => 150,
                    ],
                    'unit'          => [
                        'name'  => '单位',
                        'width' => 60,
                    ],
                    'warehouse'          => [
                        'name'  => '仓库',
                        'width' => 120,
                    ],
                    'price'          => [
                        'name'  => '单价',
                        'width' => 120,
                    ],
                    'money'          => [
                        'name'  => '金额',
                        'width' => 120,
                    ],
                    'pickNum'          => [
                        'name'  => '领料数量',
                        'width' => 120,
                    ],
                    'refundNUm'          => [
                        'name'  => '退料数量',
                        'width' => 120,
                    ]
                ];
        }
        return $tr;
    }

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        $where = self::getWarehouseSql();
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    "单据编号" => text(array("name" => "orderNo")),
                    "物料编码"   => text(array("name" => "code")),
                    "物料名称"   => text(array("name" => "materialName")),
                ],
                [
                    "业务类型"   => select(array('name'=>'type','option'=>$this->typeOption)),
                    '经手人'  =>  selectMultiple(["name" => "pickId", 'table' => "staff", 'sqlId' => 'stid', 'sqlField' => 'name', 'class' => 'width200']),
                    '仓库'  =>  selectMultiple(["name" => "warehouseId", 'table' => "warehouse", 'sqlId' => 'id', 'where' => "coid = '" . self::$coid . "' $where order by time", 'sqlField' => 'name', 'class' => 'width200']),
                ],
                [
                    "单据日期" => text(array("name" => "createTime", 'laydate' => ['type' => 'date', 'range' => '~'])),
                ]
            ]
        ],1);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

    /*列表-查询条件*/
    public function home()
    {
        $html = $this->homeOptions(false);
        //控件
        $button = "";
        if ($this->power(self::page, "export")) {
            $button .="<span class='spanButton' onclick=\"layer('importTemplate','exportFrame',{cla:'".self::page."'})\">导出</span>";
        }
        //返回
        return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button));
    }

    /*客户列表-查询结果*/
    public function homeSearch()
    {
        //like查询数组
        $like = array(
            "b.orderNo" => $this->post('orderNo'),//证件编号
            "c.name" => $this->post('materialName'),
            "c.code" => $this->post('code'),
        );
        //全等查询数组
        $equal = array(
            "b.pickId" => $this->post('pickId'),
            "a.coid"=>self::$coid,
            "b.state"=>'已确认',
            "a.warehouseId"=>$this->post('warehouseId')
        );
        $and = "";
        if ($this->post('createTime')) {
            //单据日期
            $timeArr = explode(' ~ ', $this->post('createTime'));
            $and .= " and b.recordDate >='{$timeArr[0]}' and b.recordDate <='{$timeArr[1]}'";
        }
        $and.=match ($this->post('type')){
            '生产领料'=>" and type=0",
            '生产退料'=>" and type=1",
            default=>'',
        };
        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal)) . $and;
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'a.list desc,a.time',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
        $page = $this->page(array(
            "table" => "pick_order_detail as a join pick_order as b on a.orderId = b.id join material as c on c.id = a.materialId",
            'field'=>"a.*,b.orderNo,b.recordDate,b.pickId,c.code,c.name as materialName,c.model,c.unit,b.type",
            "where" => $where,
            "order" => $orderBy['orderBy']
        ));
        $_SESSION[self::page]['sql'] = $page['fullSql'];
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("listForm", "listId")
        );
        //获取记录
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = array(
                "box" => array("name" => "listId", "value" => $array['id']),
            );
            $liButton[] = $this->dominate($dominate);
            if ($array['type']==1){
                $type = '生产退料';
                $pickNum = 0;
                $refundNUm = $array['num'];
            }else{
                $type = '生产领料';
                $pickNum = $array['num'];
                $refundNUm = 0;
            }
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case 'pickId':
                        $row[] = self::findStaff($array['pickId']);
                        break;
                    case 'type':
                        $row[] = $type;
                        break;
                    case 'warehouse':
                        $row[] = warehouseClass::getName($array['warehouseId']);
                        break;
                    case 'price':
                        $row[] = self::lostZero($array['price'],'pricePrecision');
                        break;
                    case 'money':
                        $row[] = self::lostZero($array['money']);
                        break;
                    case 'pickNum':
                        $row[] = self::lostZero($pickNum,'numPrecision');
                        break;
                    case 'refundNUm':
                        $row[] = self::lostZero($refundNUm,'numPrecision');
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        $total = find([
            'table'  => "pick_order_detail as a join pick_order as b on a.orderId = b.id join material as c on c.id = a.materialId",
            'single' => $where,
            'field'  => "sum(if(b.type=1,a.num,0))refund,sum(if(b.type=1,0,a.num))pick,sum(money)money ",
        ]);
        $total    = [
            'pickNum'        => self::lostZero($total['pick'], 'numPrecision'),
            'refundNUm'   => self::lostZero($total['refund'], 'numPrecision'),
            'money'   => self::formattingFigure($total['money']),
        ];
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
            "total"       => $total,
        ));
        //返回
        $json['html'] = $page['hint'] . "<form name='listForm'>" . $li . "</form>" . $page['button'] . clear;
        return json_encode($json, 320);
    }


    /**
     * 导出
     */
    public function exportData()
    {
        $templateId = $this->get('templateId');
        $checkedId = $this->get('checkedId')?explode(',',$this->get('checkedId')):[];
        if (!$this->power(self::page, 'export')) {
            $_SESSION['warn'] = '你还没有导出的权限';
        }  else {
            $data = [];
            /***********标题**********/
            $title =[];
            $tempFieldAll = importTemplateClass::templateField(self::page, 'exportFieldInit', id:$templateId);
            foreach ($tempFieldAll as $array) {
                if ($array['display']){
                    $title[] = $array['aliasName'];
                }
            }
            //判断是否选中导出
            if (!self::is_null_array($checkedId)){
                $result = find(array(
                    "table" => "pick_order_detail as a join pick_order as b on a.orderId = b.id join material as c on c.id = a.materialId",
                    'field'=>"a.*,b.orderNo,b.recordDate,b.pickId,c.code,c.name as materialName,c.model,c.unit,b.type",
                    "where" => "a.id in ('".implode("','", $checkedId)."') order by a.list desc,a.time desc",
                ))['array'];
            }else{
                $sql   = $_SESSION[self::page]['sql'];
                $result   = sqlFind($sql);
            }
            //导出数据生成
            foreach ($result as $array){
                $column = [];
                if ($array['type']==1){
                    $type = '生产退料';
                    $pickNum = 0;
                    $refundNUm = $array['num'];
                }else{
                    $type = '生产领料';
                    $pickNum = $array['num'];
                    $refundNUm = 0;
                }
                $warehouse = query('warehouse',"id = '$array[warehouseId]'");
                foreach ($tempFieldAll as $templateField){
                    if ($templateField['display']){
                        $column[] = match ($templateField['columnName']){
                            '单据日期'=>$array['recordDate'],
                            '单据编号'=>$array['orderNo'],
                            '业务类型'=>$type,
                            '经手人'=> self::findStaff($array['pickId']),
                            '物料编码'=>$array['code'],
                            '物料名称'=>$array['materialName'],
                            '规格型号'=>$array['model'],
                            '单位'=>$array['unit'],
                            '仓库'=>$warehouse['name'],
                            '单价'=>self::lostZero($array['price'],'pricePrecision'),
                            '金额'=>self::lostZero($array['money']),
                            '领料数量'=>self::lostZero($pickNum,'numPrecision'),
                            '退料数量'=>self::lostZero($refundNUm,'numPrecision'),
                            default=>'',
                        };
                    }
                }
                $data[] = $column;
            }
            $text = $this->control['name'] . "导出了".self::title;
            $this->logText(["type" => self::page, "text" => $text]);
            $this->excelOut($title, $data, self::title.".xlsx");
            exit(0);
        }
        header("Location:" . getenv("HTTP_REFERER"));
    }

    /**
     * 导出模板字段初始化
     * @return array[]
     */
    public function exportFieldInit($classify=''): array
    {
        return match ($classify) {
            default=>  [
                [
                    'columnName'=>'单据日期',
                    'aliasName'=>'单据日期',
                ],
                [
                    'columnName'=>'单据编号',
                    'aliasName'=>'单据编号',
                ],
                [
                    'columnName'=>'业务类型',
                    'aliasName'=>'业务类型',
                ],
                [
                    'columnName'=>'经手人',
                    'aliasName'=>'经手人',
                ],
                [
                    'columnName'=>'物料编码',
                    'aliasName'=>'物料编码',
                ],
                [
                    'columnName'=>'物料名称',
                    'aliasName'=>'物料名称',
                ],
                [
                    'columnName'=>'规格型号',
                    'aliasName'=>'规格型号',
                ],
                [
                    'columnName'=>'单位',
                    'aliasName'=>'单位',
                ],
                [
                    'columnName'=>'仓库',
                    'aliasName'=>'仓库',
                ],
                [
                    'columnName'=>'单价',
                    'aliasName'=>'单价',
                ],
                [
                    'columnName'=>'金额',
                    'aliasName'=>'金额',
                ],
                [
                    'columnName'=>'领料数量',
                    'aliasName'=>'领料数量',
                ],
                [
                    'columnName'=>'退料数量',
                    'aliasName'=>'退料数量',
                ],
            ]
        };
    }
}

